package api

import (
	"net/http"

	"gitee.com/hexug/vblog/tree/master/api/apps/user"
	"gitee.com/hexug/vblog/tree/master/api/logger"
	"github.com/gin-gonic/gin"
)

// Login 登录路由的响应函数
func (a *UserApi) Login(ctx *gin.Context) {
	//因为是通过BasicAuth的方法传入，所以这里选择用BasicAuth解析
	if username, password, ok := ctx.Request.BasicAuth(); ok {
		//如果获取到了用户名或者密码，就创建登录请求，然后登录
		request := user.NewLoginRequest(username, password)
		session, err := a.Svc.Login(ctx.Request.Context(), request)
		if err != nil {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"Code": http.StatusUnauthorized,
				"Msg":  err.Error(),
			})
			ctx.Abort()
			return
		}
		//登录成功就给请求设置两个cookie
		http.SetCookie(ctx.Writer, &http.Cookie{
			Name:     "user",
			Value:    session.UserName,
			Path:     "/",
			MaxAge:   86400,
			HttpOnly: false,
			Secure:   false,
			// SameSite: 4,
		})
		http.SetCookie(ctx.Writer, &http.Cookie{
			Name:     "uid",
			Value:    session.Id,
			Path:     "/",
			MaxAge:   86400,
			HttpOnly: false,

			Secure: false,
			// SameSite: 4,
		})
		ctx.JSON(http.StatusOK, gin.H{
			"Code": http.StatusOK,
			"Msg":  session,
		})
	}
}

// Logout 登出路由的响应函数
func (a *UserApi) Logout(ctx *gin.Context) {
	//是否登录的标识
	logined := true
	//取出cookie中的user字段
	username, err := ctx.Cookie("user")
	if err != nil {
		logger.L().Error(err.Error())
		logined = false
	}
	var session string
	//如果user字段取出成功，再去uid字段
	if logined {
		session, err = ctx.Cookie("uid")
		if err != nil {
			logger.L().Error(err.Error())
			logined = false
		}
	}
	// 无论登出是否成功，都将客户端的cookie清空
	http.SetCookie(ctx.Writer, &http.Cookie{
		Name:     "uid",
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: false,
		Secure:   false,
		// SameSite: 4,
	})
	http.SetCookie(ctx.Writer, &http.Cookie{
		Name:     "user",
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: false,
		Secure:   false,
		// SameSite: 4,
	})
	//判断前面的解析字段是否成功
	if logined {
		//解析成功，就登出
		request := user.NewLogoutRequest(session, username)
		err = a.Svc.Logout(ctx.Request.Context(), request)
		if err != nil {
			ctx.JSON(http.StatusForbidden, gin.H{
				"Code": http.StatusForbidden,
				"Msg":  err.Error(),
			})
		} else {
			ctx.JSON(http.StatusOK, gin.H{
				"Code": http.StatusOK,
				"Msg":  "Logout Success.",
			})
		}
	} else {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"Code": http.StatusBadRequest,
			"Msg":  "请求有误。",
		})
	}
}
